package valuecomusa.fijibus.eticket;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.*;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import valuecomusa.fijibus.eticket.ws.DailyCollectionItem;
import valuecomusa.fijibus.eticket.shorthaul.R;

import java.util.Date;
import java.util.List;

public class DailySummary extends SunbeamActivity
{
    private final String TAG = "DailySummary";
    private UIThreadHandler uiThreadHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Log.d(TAG, "onCreate...");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daily_summary);
        //--
        doCommon();
        //--
        TextView dateText = (TextView) findViewById(R.id.daily_summary_date_text);
        dateText.setText(Utilities.DateToString(new Date(), "EEEE dd/MM/yyyy"));
        //--

        HandlerThread uiThread = new HandlerThread("UIThreadHandler");//to prepare a looper
        uiThread.start();
        uiThreadHandler = new UIThreadHandler(uiThread.getLooper()); //to process UI such as AlertDialog,...

        GetDataWithWaitingDialog getData = new GetDataWithWaitingDialog(this);
        getData.execute();
    }

    private LinearLayout CreateLayoutRow(int bkgType, String type, String transaction, String amount)
    {
        Resources res = this.getResources();
        //--
        LinearLayout layout = new LinearLayout(DailySummary.this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        //--
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, //.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        params.gravity = Gravity.CENTER_VERTICAL;
        //--
        layout.setLayoutParams(params);
        layout.setDividerDrawable(res.getDrawable(R.drawable.list_item_divider));
        layout.setDividerPadding(1);
        layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        //layout.setBackgroundDrawable(res.getDrawable(bkgType == 1 ? R.drawable.item_background1 : R.drawable.item_background2));
        layout.setBackground(res.getDrawable(bkgType == 1 ? R.drawable.item_background1 : R.drawable.item_background2));
        //-- type
        TextView textView1 = new TextView(DailySummary.this);
        textView1.setText(type);
        params = new LinearLayout.LayoutParams(
                0,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        params.weight = 1;
        params.gravity = Gravity.LEFT;
        textView1.setLayoutParams(params);
        textView1.setPadding(5, 10, 5, 10);
        textView1.setTextColor(Color.BLACK);
        //textView1.setBackgroundColor(Color.YELLOW);
        textView1.setTextSize(22);
        layout.addView(textView1);
        //-- transaction
        TextView textView2 = new TextView(DailySummary.this);
        textView2.setText(transaction);
        params = new LinearLayout.LayoutParams(
                getDIPFromPixel(110),
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        /*params.gravity = Gravity.CENTER_HORIZONTAL;*/
        textView2.setLayoutParams(params);
        textView2.setGravity(Gravity.CENTER_HORIZONTAL);
        textView2.setPadding(5, 10, 5, 10);
        textView2.setTextColor(Color.BLACK);
        //textView2.setBackgroundColor(Color.GREEN);
        textView2.setTextSize(22);
        layout.addView(textView2);
        //-- amount
        TextView textView3 = new TextView(DailySummary.this);
        textView3.setText(amount);
        params = new LinearLayout.LayoutParams(
                getDIPFromPixel(150),
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        //params.gravity = Gravity.RIGHT;
        textView3.setLayoutParams(params);
        textView3.setGravity(Gravity.RIGHT);
        textView3.setPadding(5, 10, 30, 10);
        textView3.setTextColor(Color.BLACK);
        //textView3.setBackgroundColor(Color.BLUE);
        textView3.setTextSize(22);
        layout.addView(textView3);
        //--
        return layout;
    }

    private int getDIPFromPixel(int value)
    {
        int x = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                value,
                getResources().getDisplayMetrics());
        return x;
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        Log.d(TAG, "onStart...");

    }

    List<DailyCollectionItem> reportData;

    private void DisplayDailySummaryData()
    {
        double totalCash = 0;
        double totalVoucher = 0;
        double totalCard = 0;

        LinearLayout container = (LinearLayout) findViewById(R.id.daily_summary_item_container);
        if (reportData != null && reportData.size() > 0)
        {
            int bkgType = 2;
            for (int i = 0; i < reportData.size(); i++)
            {
                DailyCollectionItem di = reportData.get(i);
                if (di.Name.contains("Cash") || di.Name.contains("BMF Card"))
                    totalCash += di.Amount;
                else if (di.Name.contains("Student"))
                    totalVoucher += di.Amount;
                else if (di.Name.contains("Smart Card"))
                    totalCard += di.Amount;
                //--
                LinearLayout row = CreateLayoutRow(
                        i % 2 == 0 ? 2 : 1,
                        di.Name,
                        String.valueOf(di.TransactionCount),
                        WorkingSession.getInstance().decimalFormat.format(di.Amount)
                );
                container.addView(row);
            }
        } else
        {
            container.addView(CreateLayoutRow(1, "No data found", "", ""));
        }

        TextView total = (TextView) findViewById(R.id.daily_summary_total_cash);
        total.setText(WorkingSession.getInstance().decimalFormat.format(totalCash));
        total = (TextView) findViewById(R.id.daily_summary_total_voucher);
        total.setText(WorkingSession.getInstance().decimalFormat.format(totalVoucher));
        total = (TextView) findViewById(R.id.daily_summary_total_card);
        total.setText(WorkingSession.getInstance().decimalFormat.format(totalCard));
        //-
        total = (TextView) findViewById(R.id.daily_summary_grand_total);
        total.setText(WorkingSession.getInstance().decimalFormat.format(totalCash + totalCard + totalVoucher));
        //--
    }

    public class GetDataWithWaitingDialog extends AsyncTask<Void, Void, Void>
    {
        private ProgressDialog progress;
        private Context callerContext;

        public GetDataWithWaitingDialog(Context context)
        {
            callerContext = context;
        }

        public void onPreExecute()
        {
            progress = new ProgressDialog(callerContext);
            progress.setMessage("waiting...");
            progress.show();
            //--
            super.onPreExecute();
        }

        public Void doInBackground(Void... unused)
        {
            DataCenter dataCenter = new DataCenter(DailySummary.this);
            reportData = dataCenter.getDailySummaryData(
					WorkingSession.getInstance().loggedInConductor.ISN);
            if(uiThreadHandler != null)
                uiThreadHandler.sendEmptyMessage(UIThreadHandler.MSG_DATA_RECEIVED);

            return null;
        }

        public void onPostExecute(Void unused)
        {
            progress.dismiss();
            //--
            super.onPostExecute(unused);
        }
    }

    private final class UIThreadHandler extends android.os.Handler
    {
        public static final int MSG_DATA_RECEIVED = 0x10;

        public UIThreadHandler(Looper lp)
        {
            super(lp);
        }

        @Override
        public void handleMessage(Message msg)
        {
            try
            {
                switch(msg.what)
                {
                    case UIThreadHandler.MSG_DATA_RECEIVED:
                    {
                        runOnUiThread(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                DisplayDailySummaryData();
                            }
                        });

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.e(TAG, ex.getMessage());
            }
        }
    }
}
